<template>
	<view class="container">
	<view class="header">
		<text class="title">执行盘点</text>
		<view class="save-btn" @click="saveInventory">
			<text class="save-text">保存</text>
		</view>
	</view>

		<view class="content">
			<!-- 基本信息 -->
			<view class="section">
				<view class="section-title">基本信息</view>
				<view class="form-grid">
					<view class="field">
						<text class="label">计划盘点时间</text>
						<view class="input disabled">{{ inventoryInfo.plannedDate || '-' }}</view>
					</view>
					<view class="field">
						<text class="label">备件仓库</text>
						<view class="input disabled">{{ getWarehouseName(inventoryInfo.warehouseCode) }}</view>
					</view>
					<view class="field">
						<text class="label">盘点人</text>
						<view class="input disabled">{{ inventoryInfo.inventoryUser || '-' }}</view>
					</view>
				</view>
			</view>

			<!-- 备注信息 -->
			<view class="section">
				<view class="section-title">备注信息</view>
				<view class="remark-field">
					<textarea class="textarea" v-model="inventoryInfo.remark" placeholder="请输入备注信息（可选）" maxlength="200"></textarea>
					<text class="char-count">{{ (inventoryInfo.remark || '').length }}/200</text>
				</view>
			</view>

			<!-- 备件信息 -->
			<view class="section">
				<view class="section-title">备件信息</view>
				
				<!-- 备件列表 -->
				<view class="parts-list" v-if="partList.length > 0">
					<view class="part-item" v-for="(part, index) in partList" :key="index">
						<view class="part-header">
							<text class="part-name">{{ part.partName }}</text>
							<text class="part-code">{{ part.partNo }}</text>
						</view>
						<view class="part-details">
							<view class="detail-row">
								<text class="detail-label">规格型号:</text>
								<text class="detail-value">{{ part.specification || '-' }}</text>
							</view>
							<view class="detail-row">
								<text class="detail-label">备件类型:</text>
								<text class="detail-value">{{ getPartTypeName(part.partType) }}</text>
							</view>
							<view class="detail-row">
								<text class="detail-label">理论在库数:</text>
								<text class="detail-value">{{ part.theoreticalQty }}</text>
							</view>
							<view class="detail-row">
								<text class="detail-label">实际在库数:</text>
								<view class="quantity-control">
									<button class="quantity-btn minus-btn" @click="decreaseQuantity(index)">-</button>
									<input class="quantity-input" v-model.number="part.actualQty" @input="calculateDifference(index)" type="number" />
									<button class="quantity-btn plus-btn" @click="increaseQuantity(index)">+</button>
								</view>
							</view>
							<view class="detail-row">
								<text class="detail-label">盘盈数量:</text>
								<text class="detail-value" :class="part.surplusQty > 0 ? 'surplus' : ''">{{ part.surplusQty > 0 ? '+' + part.surplusQty : part.surplusQty }}</text>
							</view>
							<view class="detail-row">
								<text class="detail-label">盘亏数量:</text>
								<text class="detail-value" :class="part.lossQty > 0 ? 'loss' : ''">{{ part.lossQty > 0 ? '-' + part.lossQty : part.lossQty }}</text>
							</view>
						</view>
					</view>
				</view>
				
				<!-- 空状态 -->
				<view class="empty-parts" v-else>
					<text class="empty-text">暂无备件数据</text>
				</view>
			</view>
		</view>

		<!-- 加载状态 -->
		<view class="loading" v-if="loading">
			<text class="loading-text">加载中...</text>
		</view>
	</view>
</template>

<script>
import { getInventory, executeInventory } from '@/api/inventory/inventory.js'

export default {
	data() {
		return {
			loading: false,
			sessionNo: '',
			inventoryInfo: {},
			partList: [],
			// 备件类型列表
			partTypeList: []
		}
	},
	onLoad(options) {
		this.sessionNo = options.sessionNo
		if (this.sessionNo) {
			this.loadInventoryDetail()
		} else {
			uni.showToast({
				title: '盘点单号不能为空',
				icon: 'none'
			})
			setTimeout(() => uni.navigateBack(), 1500)
		}
	},
	methods: {
		// 加载盘点单详情
		async loadInventoryDetail() {
			try {
				this.loading = true
				console.log('加载盘点单详情，sessionNo:', this.sessionNo)
				
				// 先加载备件类型列表
				await this.loadPartTypes()
				
				const response = await getInventory(this.sessionNo)
				console.log('盘点单详情API返回:', response)
				
				if (response && response.code === 200 && response.data) {
					this.inventoryInfo = response.data
					this.partList = (response.data.partList || []).map(item => {
						console.log('处理备件数据:', item)
						return {
							...item,
							// 确保字段映射正确
							partNo: item.partNo || item.partCode || item.id,
							partName: item.partName || item.name || '-',
							specification: item.specification || item.specNo || item.spec || '-',
							partType: item.partType || item.partTypeCode || item.typeCode || 'UNKNOWN',
							theoreticalQty: item.theoreticalQty || item.quantity || 0,
							actualQty: item.actualQty || item.theoreticalQty || 0,
							surplusQty: 0,
							lossQty: 0
						}
					})
					
					// 初始化时计算差值
					this.partList.forEach((item, index) => {
						this.calculateDifference(index)
					})
					
					console.log('盘点单详情加载完成:', this.inventoryInfo)
					console.log('备件列表:', this.partList)
				} else {
					uni.showToast({
						title: '加载盘点单详情失败',
						icon: 'none'
					})
				}
			} catch (error) {
				console.error('加载盘点单详情失败:', error)
				uni.showToast({
					title: '加载失败: ' + (error.message || '未知错误'),
					icon: 'none'
				})
			} finally {
				this.loading = false
			}
		},

		// 增加数量
		increaseQuantity(index) {
			if (this.partList[index]) {
				this.partList[index].actualQty = (this.partList[index].actualQty || 0) + 1
				this.calculateDifference(index)
			}
		},

		// 减少数量
		decreaseQuantity(index) {
			if (this.partList[index] && this.partList[index].actualQty > 0) {
				this.partList[index].actualQty = this.partList[index].actualQty - 1
				this.calculateDifference(index)
			}
		},

		// 计算盘盈盘亏
		calculateDifference(index) {
			const part = this.partList[index]
			if (!part) return
			
			const theoretical = part.theoreticalQty || 0
			const actual = part.actualQty || 0
			const difference = actual - theoretical
			
			part.surplusQty = difference > 0 ? difference : 0
			part.lossQty = difference < 0 ? Math.abs(difference) : 0
		},

		// 加载备件类型列表
		async loadPartTypes() {
			try {
				console.log('开始加载备件类型列表...')
				const { listPartType } = await import('@/api/inventory/partType.js')
				const response = await listPartType({})
				console.log('备件类型API返回:', response)

				if (response && response.code === 200) {
					const types = response.rows || response.data || []
					this.partTypeList = types.map(type => ({
						code: type.code || type.typeCode || type.id,
						name: type.name || type.typeName || type.label
					}))
					console.log('备件类型列表处理完成:', this.partTypeList)
				} else {
					console.log('备件类型数据为空或格式不正确，响应:', response)
					this.partTypeList = []
				}
			} catch (e) {
				console.error('加载备件类型列表失败:', e)
				this.partTypeList = []
			}
		},

		// 获取备件类型中文名称
		getPartTypeName(typeCode) {
			if (!typeCode) return ''
			console.log('查找备件类型:', typeCode, '当前备件类型列表:', this.partTypeList)
			
			// 首先尝试从后端数据中查找
			const partType = this.partTypeList.find(type => type.code === typeCode)
			if (partType) {
				console.log('从后端数据找到备件类型:', partType.name)
				return partType.name
			}
			
			// 如果后端数据为空，使用备用映射
			const fallbackMapping = {
				'BEARING': '轴承',
				'SEAL': '密封件',
				'FILTER': '过滤器',
				'BELT': '皮带',
				'CHAIN': '链条',
				'GEAR': '齿轮',
				'VALVE': '阀门',
				'PUMP': '泵',
				'MOTOR': '电机',
				'SENSOR': '传感器',
				'CABLE': '电缆',
				'TOOL': '工具',
				'CONSUMABLE': '消耗品',
				'SPARE': '备件',
				'REPAIR': '维修件'
			}
			
			const result = fallbackMapping[typeCode] || typeCode
			console.log('备件类型映射结果:', result)
			return result
		},

		// 获取仓库名称
		getWarehouseName(code) {
			const warehouseMapping = {
				'WH001': '主仓库',
				'WH002': '备用仓库',
				'WH003': '临时仓库',
				'MAIN': '主仓库',
				'BACKUP': '备用仓库',
				'TEMP': '临时仓库'
			}
			return warehouseMapping[code] || code || '-'
		},

		// 保存盘点结果
		async saveInventory() {
			try {
				// 验证必填字段
				if (this.partList.some(item => item.actualQty == null || item.actualQty === '')) {
					uni.showToast({
						title: '请填写所有备件的实际在库数',
						icon: 'none'
					})
					return
				}

				const payload = {
					sessionNo: this.sessionNo,
					actualDate: new Date().toISOString().slice(0, 19).replace('T', ' '),
					remark: this.inventoryInfo.remark || '',
					partList: this.partList.map(part => ({
						partNo: part.partNo,
						actualQty: part.actualQty,
						surplusQty: part.surplusQty,
						lossQty: part.lossQty
					}))
				}

				console.log('提交盘点结果:', payload)

				uni.showLoading({ title: '保存中...' })
				const response = await executeInventory(payload)
				uni.hideLoading()

				if (response && response.code === 200) {
					uni.showToast({
						title: '盘点完成',
						icon: 'success'
					})
					// 延迟1秒后自动返回上一页
					setTimeout(() => {
						uni.navigateBack()
					}, 1000)
				} else {
					uni.showToast({
						title: response.msg || '保存失败',
						icon: 'none'
					})
				}
			} catch (error) {
				uni.hideLoading()
				console.error('保存盘点结果失败:', error)
				uni.showToast({
					title: '保存失败: ' + (error.message || '未知错误'),
					icon: 'none'
				})
			}
		},

		goBack() {
			uni.navigateBack()
		}
	}
}
</script>

<style scoped>
.container {
	min-height: 100vh;
	background-color: #f5f6f7;
}

.header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20rpx 30rpx;
	background: #fff;
	border-bottom: 1rpx solid #eee;
}

.save-btn {
	width: 60rpx;
	height: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.title {
	font-size: 32rpx;
	font-weight: 600;
	color: #333;
}

.save-text {
	font-size: 28rpx;
	color: #4a94ff;
	font-weight: 500;
}

.content {
	padding: 20rpx;
}

.section {
	background: #fff;
	border-radius: 16rpx;
	margin-bottom: 20rpx;
	overflow: hidden;
}

.section-title {
	font-size: 28rpx;
	font-weight: 600;
	color: #333;
	padding: 30rpx 30rpx 20rpx;
	border-bottom: 1rpx solid #f0f0f0;
}

.form-grid {
	padding: 20rpx 30rpx 30rpx;
}

.field {
	margin-bottom: 30rpx;
}

.field:last-child {
	margin-bottom: 0;
}

.label {
	font-size: 28rpx;
	color: #333;
	font-weight: 500;
	display: block;
	margin-bottom: 15rpx;
}

.input {
	width: 100%;
	height: 80rpx;
	background: #f8f9fa;
	border: 1rpx solid #e9ecef;
	border-radius: 12rpx;
	padding: 0 20rpx;
	font-size: 28rpx;
	color: #333;
	box-sizing: border-box;
	display: flex;
	align-items: center;
}

.input.disabled {
	background: #f5f5f5;
	color: #999;
}

.remark-field {
	padding: 20rpx 30rpx 30rpx;
	position: relative;
}

.textarea {
	width: 100%;
	min-height: 200rpx;
	background: #f8f9fa;
	border: 1rpx solid #e9ecef;
	border-radius: 12rpx;
	padding: 20rpx;
	font-size: 28rpx;
	color: #333;
	box-sizing: border-box;
	resize: none;
}

.char-count {
	position: absolute;
	bottom: 40rpx;
	right: 40rpx;
	font-size: 24rpx;
	color: #999;
}

.parts-list {
	padding: 20rpx;
}

.part-item {
	background: #fff;
	border-radius: 12rpx;
	margin-bottom: 20rpx;
	overflow: hidden;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.part-header {
	background: #f8f9fa;
	padding: 20rpx;
	border-bottom: 1rpx solid #eee;
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.part-name {
	font-size: 28rpx;
	font-weight: 600;
	color: #333;
}

.part-code {
	font-size: 24rpx;
	color: #666;
	background: #e9ecef;
	padding: 8rpx 16rpx;
	border-radius: 20rpx;
}

.part-details {
	padding: 20rpx;
}

.detail-row {
	display: flex;
	align-items: center;
	margin-bottom: 20rpx;
}

.detail-row:last-child {
	margin-bottom: 0;
}

.detail-label {
	font-size: 26rpx;
	color: #666;
	width: 160rpx;
	flex-shrink: 0;
}

.detail-value {
	font-size: 26rpx;
	color: #333;
	flex: 1;
}

.quantity-control {
	display: flex;
	align-items: center;
	justify-content: flex-start;
}

.quantity-btn {
	width: 60rpx;
	height: 60rpx;
	border: 1rpx solid #ddd;
	background: #fff;
	border-radius: 8rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 28rpx;
	color: #333;
	font-weight: bold;
}

.quantity-btn:active {
	background: #f0f0f0;
}

.quantity-input {
	width: 120rpx;
	height: 60rpx;
	border: 1rpx solid #ddd;
	border-radius: 8rpx;
	text-align: center;
	font-size: 26rpx;
	margin: 0 16rpx;
	background: #fff;
}

.surplus {
	color: #67C23A;
	font-weight: 600;
}

.loss {
	color: #F56C6C;
	font-weight: 600;
}

.empty-parts {
	text-align: center;
	padding: 40rpx 20rpx;
	color: #999;
}

.empty-text {
	font-size: 28rpx;
}

.loading {
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 100rpx 0;
}

.loading-text {
	font-size: 28rpx;
	color: #999;
}
</style>
